package com.yxw.im;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.logging.Logger;

/**
 * Created by hp on 2015/12/7.
 */
public class IMClientHandler extends ChannelHandlerAdapter{
    private static final Logger logger=Logger.getLogger(IMClientHandler.class.getName());

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        while(true){
            System.out.println("客户端给服务端发送信息开始");
            IMRequest request = new IMRequest();
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            request.setInfo(in.readLine());
            ctx.writeAndFlush(request);
            System.out.println("客户端给服务端发送消息结束");
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("客户端接收服务端信息开始");
        IMResponse response = (IMResponse)msg;
        System.out.println(response.getInfo());
        System.out.println("客户端接收服务端信息结束");
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
        System.out.println("客户端接收服务端信息处理结束");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.warning("Unexpected exception from downstream:"+cause.getMessage());
        ctx.close();
        System.out.println("客户端异常退出");
    }
}
